<template>
  <view class="page">
    <view>
      <view class="flex" v-if="isEidt">
        <view class="flex-1"></view>
        <button class="btn-del" @click="delFn">删除</button>
      </view>

      <view class="item flex flex-ai-c">
        <view class="requiredIcon">*</view>
        <view class="left flex-1">管理员:</view>
        <view class="right flex flex-ai-c">
          <input
            class="flex-1 right-innput"
            v-model="datas.name"
            type="text"
            maxlength="18"
            placeholder="输入姓名"
            placeholder-style="color: #999;"
            @input="nameExps"
          />
          <i-icon
            v-if="isEidt"
            icon="iconqiyebianji"
            type="single"
            size="30rpx"
            color="#999"
          ></i-icon>
        </view>
      </view>
      <view class="item flex flex-ai-c">
        <view class="requiredIcon">*</view>
        <view class="left flex-1">手机：</view>
        <input
          :disabled="isEidt"
          class="right"
          v-model="datas.phone"
          type="text"
          maxlength="11"
          placeholder="成员通过验证该手机号后可加入"
          placeholder-style="color: #999;"
          @input="phoneExps"
        />
      </view>
      <view class="item flex flex-ai-c">
        <view class="requiredIcon">*</view>
        <view class="left flex-1">管理权限：</view>
        <view
          class="right right-last flex flex-ai-c"
          :class="isOpen ? 'border1' : 'border2'"
          @click="openList"
        >
          <input
            :disabled="true"
            class="flex-1 right-innput"
            v-model="datas.stationNum"
            type="text"
            maxlength="11"
            placeholder="站点数0"
            placeholder-style="color: #999;"
          />
          <u-icon
            v-if="datas.stationNum !== '站点数0' && datas.stationNum"
            :name="isOpen ? 'arrow-down-fill' : 'arrow-up-fill'"
            size="30rpx"
            color="#999"
          ></u-icon>
          <view
            class="selectedList"
            v-show="isOpen && selectedStataionList.length"
          >
            <view
              v-for="(item, i) in selectedStataionList"
              :key="i"
              class="selected-item"
              >{{ item.station_Name }}</view
            >
          </view>
        </view>
        <button class="btn" @click="add">添加</button>
      </view>
      <view class="btn-wrap">
        <button
          class="btn-primary"
          @click="$u.debounce(submit, 500)"
          :disabled="isDisable"
        >
          {{ btnText }}
        </button>
      </view>
    </view>

    <!-- 弹框提示 -->
    <u-popup
      v-model="showPopup"
      mode="center"
      :mask="true"
      :width="popupType === 2 ? '660' : '540'"
      border-radius="20"
    >
      <view class="popup-content">
        <view class="title2" v-if="popupType === 2">选择站点</view>
        <view class="title" v-else>温馨提示</view>

        <view class="content" v-if="popupType === 0"
          >设置还未完成，是否继续编辑？</view
        >
        <view class="content" v-else-if="popupType === 1">设置保存成功！</view>
        <view class="content" v-else-if="popupType === 3"
          >成功新增管理员账号，短信已发送， 成员通过验证手机后可加入</view
        >
        <view v-else>
          <scroll-view class="list" @scrolltolower="getStationList">
            <view class="list-item" v-for="(item, i) in stationList" :key="i">
              <view>{{ item.station_Name }} </view>
              <view class="icon">
                <u-checkbox
                  v-model="item.isChecked"
                  size="42rpx"
                  icon-size="30rpx"
                  shape="circle"
                  active-color="#FBD321"
                  :label-disabled="false"
                ></u-checkbox>
              </view>
            </view>
          </scroll-view>
        </view>
        <u-line color="#eee" :hair-line="false" />
        <view
          class="btn-box flex flex-ai-c"
          v-if="popupType !== 1 && popupType !== 3"
        >
          <button class="btn-left" @click="cancel">
            {{ popupType === 0 ? "否" : "取消" }}
          </button>
          <u-line
            color="#eee"
            direction="col"
            length="40rpx"
            :hair-line="false"
          />
          <button class="btn-right" @click="okey">
            {{ popupType === 0 ? "是" : "确定" }}
          </button>
        </view>
      </view>
    </u-popup>
    <!--   删除-电话弹窗-->
    <u-popup
      v-model="showPhonePopup"
      mode="center"
      :mask="true"
      width="690"
      border-radius="20"
    >
      <view class="popup-phone">
        <view class="title">客服将协助您进行此操作</view>
        <view class="content">400-090-9987</view>
        <u-line color="#eee" :hair-line="false" />
        <view class="btn-box flex flex-ai-c">
          <button class="btn-left" @click="cancelCall">取消</button>
          <u-line
            color="#eee"
            direction="col"
            length="40rpx"
            :hair-line="false"
          />
          <button class="btn-right" @click="okeyCall">拨打</button>
        </view>
      </view>
    </u-popup>
  </view>
</template>
<script>
export default {
  data() {
    return {
      isEidt: false, //是否为编辑
      showPopup: false,
      checked: false,
      isOpen: false, //是否展开管理权限
      initData: {
        name: "", // 管理员
        stationNum: "", //站点数量
        phone: "", //电话
      },
      initSelectedStataionList: [], // 初始选中站点
      datas: {
        name: "", // 管理员
        stationNum: "", //站点数量
        phone: "", //电话
      },
      stationList: [], //站点列表
      selectedStataionList: [], //已选择的站点列表
      cancelStationList: [], //取消关联的站点列表
      btnText: "确认新增",
      popupType: 1, //弹窗内容 0 返回提示 1 保存成功 2 选择洗车点 3 新增成功 4 新增返回
      backFlag: false, //是否为弹框确认返回
      showPhonePopup: false, //删除提示
      pageIndex: 1,
      total: 0, //站点总条数
      isMore: true,
      isDisable: false,
	  id: '',
	  admin: '',
    };
  },

  computed: {
    // 店铺id
    storeId() {
      return this.$store.state.userInfoDetail.store.storeId;
    },
  },

  // 监听返回
  onBackPress(e) {
    //返回按钮
    if (!this.backFlag) {
      // 管理员姓名和手机号检查是否有修改
      for (let key in this.initData) {
        if (this.initData[key] !== this.datas[key]) {
          this.popupType = 0;
          this.showPopup = true;
          return true;
        }
      }
      // 选中站点检查是否有修改
      if (
        this.initSelectedStataionList.length !==
        this.selectedStataionList.length
      ) {
        // 长度不一致
        this.popupType = 0;
        this.showPopup = true;
        return true;
      } else if (this.initSelectedStataionList.length) {
        // 长度一致 检查每一个选中项是否与初始选中项一致
        this.initSelectedStataionList.forEach((item, index) => {
          if (item.id !== this.selectedStataionList[index].id) {
            return true;
          }
        });
      }
      return false;
    }
  },

  onLoad(e) {
    if (e.id) {
      // 编辑权限时
      uni.setNavigationBarTitle({ title: "管理账号详情" });
      this.id = e.id;
	  this.admin = e.admin;
      this.isEidt = true;
      this.btnText = "保存";
      //获取页面初始数据 和 无管理员的站点列表
      this.getCarWashManagementDetail();
    } else {
      // 新增权限 获取无管理员的站点列表
      this.getStationList();
    }
  },

  methods: {
    //获取页面初始数据
    async getCarWashManagementDetail() {
      try {
        const res = await this.$api.washCar.getCarWashManagementDetail({
          id: this.id,
        });
        // 保存初始数据
        this.initData = {
          name: res.data.admin_name,
          phone: res.data.admin_mobile,
          stationNum: "站点数" + res.data.station_num,
        };
        // 页面显示数据
        this.datas = {
          name: res.data.admin_name,
          phone: res.data.admin_mobile,
          stationNum: "站点数" + res.data.station_num,
        };
        // 获取站点列表
        this.getEditStationList(res.data.admin_mobile);
      } catch (err) {
        console.log(err);
        setTimeout(() => {
          uni.navigateBack();
        }, 3000);
      }
    },
    // 获取已有权限的站点列表 和 可选择的站点列表
    getEditStationList(mobile) {
      // 已有权限的站点列表
      let getMyStationsList = this.$api.washCar.getStationList({
        pageIndex: 1,
        pageSize: 100,
        storeid: this.storeId,
        ismanaged: true,
        mobile,
      });
      // 无管理员的站点列表
      let getNobodyStationsList = this.$api.washCar.getStationList({
        pageIndex: this.pageIndex,
        pageSize: 10,
        storeid: this.storeId,
        ismanaged: false,
        // mobile,
      });
      // 将两个列表组装为页面中的选择列表
      Promise.all([getMyStationsList, getNobodyStationsList])
        .then((res) => {
          this.total = res[1].data.total;
          this.initData.stationNum = "站点数" + res[0].data.total;
          res[0].data.list.map((item) => {
            item.isChecked = true;
          });
          this.stationList = res[0].data.list;
          this.initSelectedStataionList = res[0].data.list;
          if (res[1].data.total) {
            res[1].data.list.map((item) => {
              item.isChecked = false;
            });
            this.stationList = this.stationList.concat(res[1].data.list);
            if (this.total > this.pageIndex * 10) {
              this.pageIndex++;
              this.isMore = true;
            } else {
              this.isMore = false;
            }
          } else {
            this.isMore = false;
          }
          // 将已有权限的站点设为默认选中
          this.popupType = 2;
          this.okey();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //站点列表
    getStationList() {
      if (!this.isMore) {
        return;
      }
      this.$api.washCar
        .getStationList({
          pageIndex: this.pageIndex,
          pageSize: 10,
          storeid: this.storeId,
          ismanaged: this.isEidt, //新增false
        })
        .then((res) => {
          this.total = res.data.total;
          if (res.data.total) {
            res.data.list.map((item) => {
              item.isChecked = false;
            });

            this.stationList = this.stationList.concat(res.data.list);
          }
          if (this.total > this.pageIndex * 10) {
            this.pageIndex++;
            this.isMore = true;
          } else {
            this.isMore = false;
          }
        })
        .catch((err) => {
          console.log(err);
          uni.navigateBack();
        });
    },

    //   选择站点
    add() {
      this.isOpen = false;
      this.popupType = 2;
      this.showPopup = true;
    },

    //展开管理权限
    openList() {
      this.isOpen = !this.isOpen;
    },
    // 提交
    async submit() {
      // 数据检查
      if (!this.datas.name) {
        uni.showToast({
          title: "请输入管理员姓名",
          icon: "none",
        });
        return false;
      }
      if (!this.datas.phone) {
        uni.showToast({
          title: "请输入管理员手机号",
          icon: "none",
        });
        return false;
      }
      if (!/^1[3456789]\d{9}$/.test(this.datas.phone)) {
        uni.showToast({
          title: "请输入正确的手机号",
          icon: "none",
        });
        return false;
      }
      if (!this.selectedStataionList.length) {
        uni.showToast({
          title: "请选择站点",
          icon: "none",
        });
        return false;
      }
      this.isDisable = true;
      uni.showLoading();
      // 整理数据格式 获取用户选中的站点id列表 和 站点名称列表
      let stationIdList = [],
        stationNameList = [];
      this.selectedStataionList.forEach((item) => {
        stationIdList.push(item.id);
        stationNameList.push(item.station_Name);
      });
      let data = {
        id: this.id,
		admin_id: this.admin,
        league_id: this.storeId, //加盟商店铺id
        station_id: stationIdList, // 站点id
        station_name: stationNameList, //管理者名字
        admin_name: this.datas.name, //管理者名字
        admin_mobile: this.datas.phone, //管理者电话
        cancel_Station_id: this.cancelStationList, //  取消的站点
      };
      try {
        let res;
        if (this.isEidt) {
          // 提交修改
          res = await this.$api.washCar.editPermission(data);
          this.popupType = 1;
        } else {
          // 提交新增
          res = await this.$api.washCar.addPermission(data);
          this.popupType = 3;
        }
        if (res.data === "您已邀请，如需新增站点，请在管理界面修改站点即可！") {
          uni.showToast({
            title: res.data,
            icon: "none",
            mask: true,
            duration: 3000,
          });
        } else {
          this.showPopup = true;
          setTimeout(() => {
            this.showPopup = false;
            this.backFlag = true;
            uni.navigateBack();
          }, 3000);
        }
      } catch (err) {
        console.log(err);
      }
      this.isDisable = false;
      uni.hideLoading();
    },

    // 关闭弹窗
    cancel() {
      if (this.popupType === 0) {
        // 确认返回
        this.backFlag = true;
        uni.navigateBack();
      } else {
        this.showPopup = false;
      }
    },
    // 弹窗确认
    okey() {
      this.showPopup = false;
      if (this.popupType === 0) {
        // 继续编辑
        this.showPopup = false;
      } else if (this.popupType === 2) {
        // 选择洗车点
        this.selectedStataionList = this.stationList.filter((item) => {
          return item.isChecked;
        });
        this.datas.stationNum = "站点数" + this.selectedStataionList.length;
        // 保存默认已有权限 但 用户手动取消选中的站点
        this.cancelStationList = [];
        let flag = false;
        this.initSelectedStataionList.forEach((item) => {
          flag = false;
          for (let i = 0; i < this.selectedStataionList.length; i++) {
            if (item.id === this.selectedStataionList[i].id) {
              flag = true;
              break;
            }
          }
          if (!flag) {
            this.cancelStationList.push(item.id);
          }
        });
      }
    },

    //删除
    delFn() {
      this.showPhonePopup = true;
    },

    // 关闭删除提示弹窗
    cancelCall() {
      this.showPhonePopup = false;
    },
    // 拨打客服电话
    okeyCall() {
      this.showPhonePopup = false;
      uni.makePhoneCall({
        phoneNumber: "4000909987￥",
      });
    },

    //姓名输入验证
    nameExps(e) {
      const data = e.detail.value;
      const reg =
        /[`~!@#$€£·'%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、A-Za-z0-9]+$/im;

      setTimeout(() => {
        this.datas.name = data.replace(reg, "");
      }, 50);
    },

    phoneExps(e) {
      const data = e.detail.value;
      // const reg = new RegExp("[\u4E00-\u9FA5A-Za-z]+$");
      const reg =
        /[`~!@#$€£·'%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、\u4E00-\u9FA5A-Za-z]+$/im;

      setTimeout(() => {
        this.datas.phone = data.replace(reg, "");
      }, 10);
    },
  },
};
</script>
<style lang="scss" scoped>
.page {
  background: #fff;

  .item {
    padding: 10rpx 30rpx;
    font-size: 28rpx;
    .requiredIcon {
      color: #f30000;
    }
    .left {
      font-weight: 500;
      color: #333;
    }

    .right {
      width: 530rpx;
      height: 90rpx;
      //   line-height: 90rpx;
      padding: 0 20rpx;
      border: 2rpx solid #eeeeee;
      border-radius: 16rpx;

      .right-innput {
        height: 90rpx;
      }
    }

    .right-last {
      position: relative;
      width: 410rpx;
      height: 90rpx;
      //   line-height: 90rpx;
      padding-left: 20rpx;
      border: 2rpx solid #eeeeee;
    }

    .border1 {
      border-radius: 16rpx 16rpx 0 0;
    }

    .border2 {
      border-radius: 16rpx;
    }

    .selectedList {
      position: absolute;
      top: 88rpx;
      left: -2rpx;
      width: 410rpx;
      border: 2rpx solid #eee;
      border-top: none;
      border-radius: 0 0 16rpx 16rpx;
      font-size: 24rpx;
      font-weight: 500;
      color: #666666;
      padding-left: 20rpx;
      padding-bottom: 38rpx;

      .selected-item {
        padding-top: 38rpx;
      }
    }

    .btn {
      width: 120rpx;
      background: #fff;
      color: #38acff;
      font-size: 28rpx;
      height: 90rpx;
      line-height: 90rpx;
    }
  }

  .btn-del {
    width: 120rpx;
    color: #f30000;
    font-size: 28rpx;
    height: 60rpx;
    line-height: 60rpx;
    background: #fff;
  }

  .btn-wrap {
    position: fixed;
    bottom: 40rpx;
    left: 0;
    right: 0;
  }
}
// 提示弹框
.popup-content {
  padding-top: 30rpx;
  text-align: center;

  .title {
    font-size: 34rpx;
    font-weight: bold;
    color: #333333;
  }

  .title2 {
    font-size: 34rpx;
    font-weight: 500;
    color: #333333;
    padding-bottom: 30rpx;
    border-bottom: 2rpx solid #eee;
  }

  .content {
    padding: 30rpx 0 40rpx;
    font-size: 28rpx;
    font-weight: 500;
    color: #666666;
  }

  .list {
    height: 500rpx;
    padding: 0 30rpx;

    .list-item {
      position: relative;
      height: 98rpx;
      line-height: 98rpx;
      font-size: 30rpx;
      font-weight: 500;
      color: #333333;
      border-bottom: 2rpx solid #eee;

      .icon {
        position: absolute;
        right: 0;
        bottom: 0;
        height: 98rpx;
        width: 48rpx;
      }

      // &:not(:last-child) {
      //   border-bottom: 2rpx solid #eee;
      // }
    }
  }

  .btn-box {
    .btn {
      height: 100rpx;
      font-size: 28rpx;
      color: #999;
    }

    .btn-left {
      width: 50%;
      height: 78rpx;
      font-size: 30rpx;
      background: #fff;
      color: #999;
    }

    .btn-right {
      width: 50%;
      height: 78rpx;
      font-size: 30rpx;
      color: #38acff;
      background: #fff;
    }
  }
}

// 删除提示弹框
.popup-phone {
  // padding: 30rpx 0;
  text-align: center;

  .title {
    padding-top: 28rpx;
    font-size: 26rpx;
    font-weight: 500;
    color: #666;
  }

  .content {
    padding: 40rpx 0;
    font-size: 36rpx;
    font-weight: 500;
    color: #38acff;
  }

  .btn-box {
    .btn {
      height: 100rpx;
      font-size: 28rpx;
      color: #999;
    }

    .btn-left {
      width: 50%;
      height: 78rpx;
      font-size: 30rpx;
      background: #fff;
      color: #999;
    }

    .btn-right {
      width: 50%;
      height: 78rpx;
      font-size: 30rpx;
      color: #38acff;
      background: #fff;
    }
  }
}

/deep/ uni-button:after {
  border: none;
}

/deep/ uni-checkbox .uni-checkbox-input {
  border-radius: 50%;
}
</style>
